//
//  PopoverView.m
//  ArrowView
//
//  Created by guojiang on 4/9/14.
//  Copyright (c) 2014年 LINAICAI. All rights reserved.
//

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com

#import "PopoverView.h"


#define kArrowHeight 10.f
#define kArrowCurvature 6.f
#define SPACE 2.f
#define ROW_HEIGHT 36.f
#define TITLE_FONT [UIFont systemFontOfSize:13]
#define RGB(r, g, b)    [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:1.f]

@interface PopoverView ()<UITableViewDataSource, UITableViewDelegate>
{
    BOOL isAnimationFinished;

}
@property (nonatomic) CGPoint showPoint;

@property (nonatomic, strong) UIButton *handerView;

@end

@implementation PopoverView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.borderColor = [ClassMethodsViewController colorWithHexString:BORDERCOLOR];
        self.backgroundColor = [UIColor clearColor];
        isAnimationFinished = YES;
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadTag) name:kDidGetAndStoreNoticeNotification object:nil];
        
    }
    return self;
}
-(void)loadTag{
    [self.tableView reloadData];
}

-(id)initWithPoint:(CGPoint)point titles:(NSArray *)titles images:(NSArray *)images
{
    self = [super init];
    if (self) {
        self.showPoint = point;
        self.titleArray = titles;
        self.imageArray = images;
        
        self.frame = [self getViewFrame];
        
        [self addSubview:self.tableView];
        
    }
    return self;
}
-(id)initWithPoint:(CGPoint)point titles:(NSArray *)titles images:(NSArray *)images selectImage:(NSArray *)selectImages
{
    self = [super init];
    if (self) {
        self.showPoint = point;
        self.titleArray = titles;
        self.imageArray = images;
        self.selectImageArray = [selectImages isEqual:[NSNull null]] ? nil : selectImages;
        
        self.frame = [self getViewFrame];
        
        [self addSubview:self.tableView];
        
    }
    return self;
}

-(id)initWithPoint:(CGPoint)point titlesDict:(NSDictionary *)titlesDict imagesDict:(NSDictionary *)imagesDict{
    self = [super init];
    if (self) {
        self.showPoint = point;
        
    }
    return self;
}


-(CGRect)getViewFrame
{
    CGRect frame = CGRectZero;
    
    frame.size.height = [self.titleArray count] * ROW_HEIGHT + SPACE + kArrowHeight+1;
    
    for (NSString *title in self.titleArray) {
        CGFloat width =  [title sizeWithFont:TITLE_FONT constrainedToSize:CGSizeMake(300, 100) lineBreakMode:NSLineBreakByCharWrapping].width;
        frame.size.width = MAX(width, frame.size.width);
    }
    
    if ([self.titleArray count] == [self.imageArray count]) {
        frame.size.width = 10 + 25 + 10 + frame.size.width + 40;
    }else{
        frame.size.width = 10 + frame.size.width + 40;
    }
    
    frame.origin.x = self.showPoint.x - frame.size.width/2;
    frame.origin.y = self.showPoint.y;
    
    //左间隔最小5x
    if (frame.origin.x < 5) {
        frame.origin.x = 5;
    }
    //右间隔最小5x
    if ((frame.origin.x + frame.size.width) > kScreenWidth-5) {
        frame.origin.x = kScreenWidth-5 - frame.size.width;
    }
    
    return frame;
}


-(void)show
{
  
    
    if (isAnimationFinished == YES) {
        isAnimationFinished = NO;
        
        self.handerView = [UIButton buttonWithType:UIButtonTypeCustom];
        [_handerView setFrame:[UIScreen mainScreen].bounds];
        [_handerView setBackgroundColor:[UIColor clearColor]];
        [_handerView addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        [_handerView addSubview:self];
//        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        
        [[[UIApplication sharedApplication].delegate window] addSubview:_handerView];
        
        CGPoint arrowPoint = [self convertPoint:self.showPoint fromView:_handerView];
        self.layer.anchorPoint = CGPointMake(arrowPoint.x / self.frame.size.width, arrowPoint.y / self.frame.size.height);
        self.frame = [self getViewFrame];
        
        self.alpha = 0.f;
        self.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
//        [UIView animateWithDuration:0.2f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.transform = CGAffineTransformMakeScale(1.05f, 1.05f);
            self.alpha = 1.f;
//        } completion:^(BOOL finished) {
//            [UIView animateWithDuration:0.08f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
                self.transform = CGAffineTransformIdentity;
//            } completion:^(BOOL finished) {
                isAnimationFinished = YES;
//            }];
//        }];
    }
}

-(void)dismiss
{
    [self dismiss:YES];
}

-(void)dismiss:(BOOL)animate
{
    if (isAnimationFinished == YES) {
        isAnimationFinished = NO;
        if (!animate) {
            [_handerView removeFromSuperview];
            return;
        }
        
//        [UIView animateWithDuration:0.3f animations:^{
            self.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
            self.alpha = 0.f;
//        } completion:^(BOOL finished) {
            isAnimationFinished = YES;
            [_handerView removeFromSuperview];
//        }];
    }
}



#pragma mark - UITableView

-(UITableView *)tableView
{
    if (_tableView != nil) {
        return _tableView;
    }
    
    CGRect rect = self.frame;
    rect.origin.x = SPACE;
    rect.origin.y = kArrowHeight + SPACE;
    rect.size.width -= SPACE * 2;
    rect.size.height -= (SPACE - kArrowHeight);
    
    self.tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.alwaysBounceHorizontal = NO;
    _tableView.alwaysBounceVertical = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.scrollEnabled = NO;
    _tableView.backgroundColor = [UIColor clearColor];
//    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    
    return _tableView;
}

#pragma mark - UITableView DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_titleArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.textColor = [ClassMethodsViewController colorWithHexString:TEXT_COLOR];

    cell.backgroundView = [[UIView alloc] init];
    cell.selectedBackgroundView.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_SELECT_BACKCOLOR];
    cell.backgroundView.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_BACKCOLOR_16];
    
    if ([_imageArray count] == [_titleArray count]) {
        cell.imageView.image = [UIImage imageNamed:[_imageArray objectAtIndex:indexPath.row]];
    }
    
    if ([_selectImageArray count] == [_titleArray count]) {
        cell.imageView.highlightedImage = [UIImage imageNamed:[_selectImageArray objectAtIndex:indexPath.row]];
    }
    cell.textLabel.font = TITLE_FONT;
    cell.textLabel.text = [_titleArray objectAtIndex:indexPath.row];
    cell.textLabel.highlightedTextColor= [ClassMethodsViewController colorWithHexString:SELECT_BORDERCOLOR];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    
    
    for (UIView *view in cell.contentView.subviews) {
        if (view.tag==100002) {
            [view removeFromSuperview];
        }
    }
    
    MyNSLog("%@", cell.textLabel.text);
    if ([cell.textLabel.text isEqualToString:@"与我相关"]) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont boldSystemFontOfSize:12];
        

        
        if ( [[[SystemMessageCenter instance] selectAllNoReadedSecretaryNoticeMessage] count]>0) {
            label.text =[NSString stringWithFormat:@"%d",[[[SystemMessageCenter instance] selectAllNoReadedSecretaryNoticeMessage] count]];
//        if ( 1>0) {
//            label.text =[NSString stringWithFormat:@"%d",1];
            [label sizeToFit];
            label.tag =100002;
            label.layer.cornerRadius = label.frame.size.height/2;
            label.layer.masksToBounds = YES;
            label.layer.backgroundColor = [UIColor redColor].CGColor;
            
            label.textAlignment = NSTextAlignmentCenter;
            if (label.frame.size.width<label.frame.size.height) {
                label.frame = CGRectMake(100, (cell.frame.size.height-label.frame.size.height)/2-5, label.frame.size.height, label.frame.size.height);
                
            }else{
                
                label.frame = CGRectMake(100, (cell.frame.size.height-label.frame.size.height)/2-5, label.frame.size.width, label.frame.size.height);
            }
            [cell.contentView addSubview:label];
            
        }
        
        
        
    }
    
    
    return cell;
}

#pragma mark - UITableView Delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.selectRowAtIndex) {
        self.selectRowAtIndex(indexPath.row);
    }
    [self dismiss:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ROW_HEIGHT;
}



// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    [self.borderColor set]; //设置线条颜色
    
    CGRect frame = CGRectMake(0, 10, self.bounds.size.width, self.bounds.size.height - kArrowHeight);
    
    float xMin = CGRectGetMinX(frame);
    float yMin = CGRectGetMinY(frame);
    
    float xMax = CGRectGetMaxX(frame);
    float yMax = CGRectGetMaxY(frame);
    
    CGPoint arrowPoint = [self convertPoint:self.showPoint fromView:_handerView];
    
    UIBezierPath *popoverPath = [UIBezierPath bezierPath];
    [popoverPath moveToPoint:CGPointMake(xMin, yMin)];//左上角
    
    /********************向上的箭头**********************/
//    [popoverPath addLineToPoint:CGPointMake(arrowPoint.x - kArrowHeight, yMin)];//left side
//    [popoverPath addCurveToPoint:arrowPoint
//                   controlPoint1:CGPointMake(arrowPoint.x - kArrowHeight + kArrowCurvature, yMin)
//                   controlPoint2:arrowPoint];//actual arrow point
//    
//    [popoverPath addCurveToPoint:CGPointMake(arrowPoint.x + kArrowHeight, yMin)
//                   controlPoint1:arrowPoint
//                   controlPoint2:CGPointMake(arrowPoint.x + kArrowHeight - kArrowCurvature, yMin)];//right side
    MyNSLog("%f,%f,%f,%f",self.showPoint.x,self.showPoint.y , arrowPoint.x,arrowPoint.y);

    
    MyNSLog("%f", arrowPoint.x - kArrowHeight);
    MyNSLog("%f",arrowPoint.x  - kArrowCurvature);
    MyNSLog("%f",arrowPoint.x + kArrowCurvature);
    MyNSLog("%f",yMin);
    MyNSLog("%f,%f",arrowPoint.x,arrowPoint.y);



    

    
    
    [popoverPath addLineToPoint:CGPointMake(arrowPoint.x - kArrowHeight+4, yMin)];//left side1
    
    
    
//    [popoverPath addLineToPoint:CGPointMake(arrowPoint.x  - kArrowCurvature, yMin)];//1
//    [popoverPath addLineToPoint:arrowPoint];//2
//    
//    [popoverPath addLineToPoint:CGPointMake(arrowPoint.x + kArrowCurvature, yMin)];//3
    
    
    [popoverPath  addCurveToPoint:CGPointMake(arrowPoint.x + kArrowHeight-2, yMin) controlPoint1:CGPointMake(arrowPoint.x+4, 0) controlPoint2:CGPointMake(arrowPoint.x, 0)];
    [popoverPath addLineToPoint:CGPointMake(xMax, yMin)];
    
    
    
    /********************向上的箭头**********************/
    
    
    [popoverPath addLineToPoint:CGPointMake(xMax, yMin)];//右上角
    
    [popoverPath addLineToPoint:CGPointMake(xMax, yMax)];//右下角
    
    [popoverPath addLineToPoint:CGPointMake(xMin, yMax)];//左下角
    
    //填充颜色
    [[ClassMethodsViewController colorWithHexString:LEFT_BACKCOLOR_16] setFill];
    [popoverPath fill];
    
    [popoverPath closePath];
    [popoverPath stroke];
}


@end
